//
//  TestADTextViewController.swift
//  ADKit_Example
//
//  Created by Adoma on 2023/12/27.
//  Copyright © 2023 CocoaPods. All rights reserved.
//

import ADKit
import RxSwift
import RxCocoa
import IQKeyboardToolbarManager

class TestADTextViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "测试ADTextView字数限制功能"
        view.backgroundColor = ADKit.Color.k0170C9
        
        //        let textView = ADTextView(placeHolder: "placeHolder", maxCount: 10)
        //        view.addSubview(textView)
        //        textView.snp.makeConstraints { make in
        //            make.top.equalTo(self.view.snp.topMargin).offset(30)
        //            make.left.right.equalToSuperview().inset(16)
        //            make.height.equalTo(120)
        //        }
        
        let textfield = UITextField()
        textfield.iq.isEnableToolBar = false
//        textfield.textLimit = 10
        textfield.backgroundColor = .random
        view.addSubview(textfield)
        textfield.snp.makeConstraints { make in
            make.top.equalTo(self.view.snp.topMargin).offset(30)
            make.left.right.equalToSuperview().inset(16)
            make.height.equalTo(120)
        }
        
//        textfield.inputLimitSubject
//            .subscribe { text in
//                debugPrint(text)
//            }.disposed(by: rx.disposeBag)
        
//        let limitSubject = textfield.inputLimitSubject.compactMap({ $1 })
        
        let textSubject = BehaviorSubject(value: "")
//
        let limitSubject = textSubject.filter({[weak textfield] _ in
            textfield?.markedTextRange == nil
        }).map({ text in
            return text.substring(to: 9)
        }).share(replay: 1)
//        
        limitSubject.bind(to: textfield.rx.text).disposed(by: rx.disposeBag)
        textfield.rx.text.orEmpty.bind(to: textSubject).disposed(by: rx.disposeBag)
        
        DispatchQueue.main.after(time: 2) {
            textSubject.onNext("123123123")
//            textfield.text = "123123123"
        }
        
        let count = UILabel(font: .systemFont(ofSize: 15), color: ADKit.Color.k333333)
        view.addSubview(count)
        count.snp.makeConstraints { make in
            make.bottom.right.equalTo(textfield).inset(16)
        }
        
        limitSubject.map({ "\($0.count.toString)/10" }).bind(to: count.rx.text).disposed(by: rx.disposeBag)
    }
}

